 var path = require('path');

 var fs = require('fs');


 var zipInstall = require('./zip-install');

 var util = require('util');

 var multiparty = require('multiparty');

 module.exports = function (UC, source, config, ArFor, cache, package) {

     var user_extend = config.user_extend;
     var source = config.Source;
     var UserControl = UC;
     var openjson = config.openjson;
     var RemoveFile = function (File) {
         fs.exists(File, function (exists) {
             if (exists) {
                 var shell = require('shelljs');
                 shell.rm('-rf', File);
             }
         })
     }

     var PluginUpload = function (req, Callback) {
         var body = UserControl.GetForm(req.session.key, {
             UploadFile: 4
         }); 
         new source("M_681", body, function (db) {
             if (db) {
                 var uploadDir = path.join(config.Files.Temp, "images/");
                 uploadDir = path.join(uploadDir, '');
                 var form = new multiparty.Form({
                     uploadDir: uploadDir
                 });
                 //上传完成后处理
                 form.parse(req, function (err, fields, files) {
                     var value = {
                         error: 113
                     };
                     if (err == null) {
                         var filesTmp = JSON.stringify(files, null, 2);
                         var ut = util.inspect({
                             fields: fields,
                             files: filesTmp
                         });
                         var item = files.files[0];
                         var _path = item.path;

                         var targetPath = config.Files.Plugin;

                         var localpath = _path.replace(uploadDir, "").replace(".zip", "");

                         body.localpath = localpath;
                         body.zipfile = _path;

                         zipInstall(source,body,config,function(value){

                            Callback(value);
                         }) 
                         
                     } else {
                         Callback(value);
                     }

                 });
             } else {
                 var value = {
                     error: 114
                 };
                 Callback(value);
             }
         })
     };
     var router = function (req, res, next) {
         var FileType = 1;
         var query = req.query;
         if (query.FileType == "4") {
             PluginUpload(req, function (value) {
                 res.Json(value);
             });
         } else {
             var value = {
                 error: 108
             };
             res.Json(value);
         }



     };
     return router;
 }